/*
 * Copyright 2002-2016 the Beijing Brain Technology co.,LTD http://www.bris.cn/
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bris.niosocket.handler;

import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;

import com.bris.niosocket.mapping.SocketDispather;
import com.bris.niosocket.mapping.SpringContextHelper;
import com.bris.niosocket.message.impl.RequestMessage;
import com.bris.niosocket.message.impl.ResponseMessage;

/**
 * 承载业务线程,处理业务逻辑</br> 从此处起接管由Netty IO线程以及解码的业务数据,Netty io线程返回其IO线程池,业务线程池
 * 开始接受并执行业务逻辑。</br> 2016年2月16日</br>
 * 
 * @author xunaidong
 * @since 1.0.0
 */
public class TaskWorker implements Runnable {
	
	private ChannelHandlerContext channelContext;
	private RequestMessage request;

	public TaskWorker(ChannelHandlerContext context, RequestMessage messge) {
		this.channelContext = context;
		this.request = messge;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Runnable#run()
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void run() {
		ResponseMessage response = new ResponseMessage();
		response.setSerialNumber(request.getSerialNumber());
		try {
			SpringContextHelper.getBean(SocketDispather.class).doDispath(request, response);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		channelContext.writeAndFlush(response).addListeners(ChannelFutureListener.CLOSE);
	}

}
